package com.qcu.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qcu.dto.LoginDto;
import com.qcu.dto.RegisterDto;
import com.qcu.entity.StaffAccount;
import com.qcu.entity.User;
import com.qcu.exception.RepeatException;
import com.qcu.service.LoginService;
import com.qcu.service.StaffAccountService;
import com.qcu.service.UserService;
import com.qcu.util.PasswordUtils;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Name: MyComputer
 * @ClassName UserController
 * @Description: TODO: 进行操作前需要验证居民是否被当前用户所包含
 * @date 2025/2/6 13:10
 */
@RestController
@RequestMapping("/user/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private StaffAccountService staffAccountService;

    @Resource(name = "PlainLoginService")
    private LoginService plainLoginService;

    @Resource(name = "StaffLoginService")
    private LoginService staffLoginService;

    @Resource
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    RedisTemplate redisTemplate;


    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Response register(@RequestBody RegisterDto user) throws RepeatException {

        try {
            return userService.saveUser(user);
        } catch (Exception e) {
            throw new RepeatException(e.getMessage());

        }
    }

    //todo:用户登录
    @PostMapping("/login")
    public Response login(@RequestBody LoginDto loginDto, HttpSession session) {

        if (loginDto.getType().equals("USER")) {
            return plainLoginService.login(loginDto);
        } else if (loginDto.getType().equals("STAFF") || loginDto.getType().equals("ADMIN") || loginDto.getType().equals("PLAIN")) {
            return staffLoginService.login(loginDto);
        }
        return Response.failure(ResponseCode.FAILURE, "登录失败");
    }

    @GetMapping("/getEmailCode")
    public Response getEmailCode(@RequestParam(name = "username") String username) {
        String verificationCode = generateVerificationCode();

        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        String email = one.getEmail();

        // 将验证码存储到Redis中，设置过期时间（例如5分钟）
        redisTemplate.opsForValue().set(email, verificationCode, 1, TimeUnit.MINUTES);

        // 发送验证码邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(email);
        mailMessage.setSubject("验证码");
        mailMessage.setText("您的验证码是: " + verificationCode);
        javaMailSender.send(mailMessage);

        return Response.success("验证码已发送");
    }

    @PostMapping("/restPwd")
    public Response restPwd(@RequestParam(name = "username") String username, @RequestParam(name = "code") String code) {
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        String email = one.getEmail();

        String verificationCode = (String) redisTemplate.opsForValue().get(email);
        boolean update = false;
        if (verificationCode.equals(code)) {
            String salt = PasswordUtils.generateSalt();
            String hashPassword = PasswordUtils.hashPassword("123456", salt);
            update = userService.update(new LambdaUpdateWrapper<User>().set(User::getSalt, salt).set(User::getPasswordHash, hashPassword).eq(User::getUsername, username));

            // 发送验证码邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setTo(email);
            mailMessage.setSubject("密码重置");
            mailMessage.setText("您的密码是: 123456 请及时登录修改");
            javaMailSender.send(mailMessage);
        }
        return update ? Response.success() : Response.failure(ResponseCode.FAILURE, "密码重置失败");
    }

    @GetMapping("/getUserInfo")
    public Response getUserInfo() {
        Map<String, Object> claim = ThreadLocalUtil.get();
        String role = (String) claim.get("role");
        String username = (String) claim.get("username");
        if (role.equals("USER")) {
            return Response.success(userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username)));
        } else if (role.equals("STAFF") || role.equals("ADMIN") || role.equals("PLAIN")) {
            return Response.success(staffAccountService.getOne(new LambdaQueryWrapper<StaffAccount>().eq(StaffAccount::getUsername, username)));
        }
        return Response.failure(ResponseCode.FAILURE, "获取用户信息失败");
    }

    @PutMapping("/update")
    public Response updateUserInfo(@RequestParam(required = false) String username, @RequestParam(required = false) String email, @RequestParam(required = false) String password, @RequestParam(required = false) String position, @RequestParam(required = false) String firstName, @RequestParam(required = false) String lastName) {
        Map<String, Object> claim = ThreadLocalUtil.get();
        String role = (String) claim.get("role");
        Integer id = (Integer) claim.get("id");
        if (role.equals("USER")) {
            if (username != null) {
                return Response.success(userService.update(new LambdaUpdateWrapper<User>().set(User::getUsername, username).eq(User::getId, id)));
            }
            if (email != null) {
                return Response.success(userService.update(new LambdaUpdateWrapper<User>().set(User::getEmail, email).eq(User::getId, id)));
            }
            if (password != null) {
                String salt = PasswordUtils.generateSalt();
                String hashPassword = PasswordUtils.hashPassword(password, salt);
                return Response.success(userService.update(new LambdaUpdateWrapper<User>().set(User::getSalt, salt).set(User::getPasswordHash, hashPassword).eq(User::getId, id)));
            }
            if (position != null) {
                return Response.success(userService.update(new LambdaUpdateWrapper<User>().set(User::getPosition, position).eq(User::getId, id)));
            }
        } else if (role.equals("STAFF") || role.equals("ADMIN") || role.equals("PLAIN")) {
            if (username != null) {
                return Response.success(staffAccountService.update(new LambdaUpdateWrapper<StaffAccount>().set(StaffAccount::getUsername, username).eq(StaffAccount::getStaffId, id)));
            }
            if (email != null) {
                return Response.success(staffAccountService.update(new LambdaUpdateWrapper<StaffAccount>().set(StaffAccount::getEmail, email).eq(StaffAccount::getStaffId, id)));
            }
            if (password != null) {
                String salt = PasswordUtils.generateSalt();
                String hashPassword = PasswordUtils.hashPassword(password, salt);
                return Response.success(staffAccountService.update(new LambdaUpdateWrapper<StaffAccount>().set(StaffAccount::getSalt, salt).set(StaffAccount::getPasswordHash, hashPassword).eq(StaffAccount::getStaffId, id)));
            }
            if (firstName != null) {
                return Response.success(staffAccountService.update(new LambdaUpdateWrapper<StaffAccount>().set(StaffAccount::getFirstName, firstName).eq(StaffAccount::getStaffId, id)));
            }
            if (lastName != null) {
                return Response.success(staffAccountService.update(new LambdaUpdateWrapper<StaffAccount>().set(StaffAccount::getLastName, lastName).eq(StaffAccount::getStaffId, id)));
            }

        }

        return Response.failure(ResponseCode.FAILURE, "更新用户信息失败");


    }

    /**
     * 生成四位随机数验证码
     *
     * @return 四位随机数验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        int code = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数
        return String.valueOf(code);
    }

//    @GetMapping("/send")
//    public Response sendEmail(){
//        SimpleMailMessage mailMessage = new SimpleMailMessage();
//        mailMessage.setFrom(from);
//        mailMessage.setTo("488537248@qq.com","");
//        mailMessage.setSubject("测试邮件");
//        mailMessage.setText("测试邮件内容");
//        javaMailSender.send(mailMessage);
//        System.out.println("邮件发送成功");
//        return Response.success();
//    }
}
